package ar.edu.uba.fi.jmit.aspecter.parser.parsers;

import java.util.ArrayList;
import java.util.List;

import ar.edu.uba.fi.jmit.aspecter.core.Constants;
import ar.edu.uba.fi.jmit.aspecter.core.WeavingInstrumentor;
import ar.edu.uba.fi.jmit.aspecter.core.WeavingInstrumentorFactory;
import ar.edu.uba.fi.jmit.aspecter.parser.configurations.ConfigurationConstructor;
import ar.edu.uba.fi.jmit.aspecter.parser.configurations.ConfigurationMethod;
import ar.edu.uba.fi.jmit.aspecter.parser.configurations.Param;
import ar.edu.uba.fi.jmit.aspecter.parser.exception.XMLParserRuntimeException;

public class InvocationCounterMonitorParse extends MonitorParse {
	
	public WeavingInstrumentor closeMonitor(String enviromentSelected) throws ClassNotFoundException {
		if (!this.applyParse(enviromentSelected)){
			return null;
		}
		
		ConfigurationMethod confMethod = (ConfigurationMethod)this.configurations.getConfiguration(Constants.METHOD);
		
		if (confMethod!=null){
			List<Class<?>> clazzs = null;
			if (!confMethod.isAllMethods()){
				clazzs = new ArrayList<Class<?>>();
				for (Param param : confMethod.getParameters()) {
					clazzs.add(this.getClassForName(param.type));
				}
			}
			return WeavingInstrumentorFactory.getInstance().getInvocationCounterInstrumentor(this.monitorName,
					this.getClassForName(confMethod.getClassName()), confMethod.getMethodName(), confMethod.getId(), clazzs, this.getClassForName(confMethod.getReturnType()), this.priority);			
		}
		
		ConfigurationConstructor confConstructor = (ConfigurationConstructor) this.configurations.getConfiguration(Constants.CONSTRUCTOR);
		
		if (confConstructor!=null){
			List<Class<?>> clazzs = null;
			if (!confConstructor.isAllMethods()){
				clazzs = new ArrayList<Class<?>>();
				for (Param param : confConstructor.getParameters()) {
					clazzs.add(this.getClassForName(param.name));
				}
			}
			return WeavingInstrumentorFactory.getInstance().getInvocationCounterInstrumentor(this.monitorName, 
					this.getClassForName(confConstructor.getClassName()), confConstructor.getId(), clazzs, this.priority);
		}
		
		throw new XMLParserRuntimeException("Tag constructor or tag method are missing");
	}
	
}
